/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.persistence.hibernate;

import com.whirlycott.cache.Cache;
import com.whirlycott.cache.CacheManager;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.Timestamper;

import java.util.Collections;
import java.util.Map;

public class WhirlyCache implements org.hibernate.cache.Cache {
  private String name;
  private Cache cache;

  public WhirlyCache(String name) {
    this.name = name;
    try {
      this.cache = CacheManager.getInstance().getCache(name);
    } catch (com.whirlycott.cache.CacheException e) {
      throw new CacheException(e);
    }
  }

  public Object get(Object key) throws CacheException {
    return cache.retrieve(key);
  }

  public Object read(Object key) throws CacheException {
    return get(key);
  }

  public void put(Object key, Object value) throws CacheException {
    cache.store(key, value);
  }

  public void update(Object key, Object value) throws CacheException {
    put(key, value);
  }

  public void remove(Object key) throws CacheException {
    cache.remove(key);
  }

  public void clear() throws CacheException {
    cache.clear();
  }

  public void destroy() throws CacheException {
    try {
      CacheManager.getInstance().destroy(name);
    } catch (com.whirlycott.cache.CacheException e) {
      throw new CacheException(e);
    } finally {
      cache = null;
    }
  }

  public void lock(Object object) throws CacheException {
  }

  public void unlock(Object object) throws CacheException {
  }

  public long nextTimestamp() {
    return Timestamper.next();
  }

  public int getTimeout() {
    return Timestamper.ONE_MS * 60000;
  }

  public String getRegionName() {
    return "WhirlyCache-" + name;
  }

  public long getSizeInMemory() {
    return 0;
  }

  public long getElementCountInMemory() {
    return cache.size();
  }

  public long getElementCountOnDisk() {
    return 0;
  }

  public Map toMap() {
    return Collections.emptyMap();
  }
}
